#include "StdAfx.h"
#include "BasicWindowLessMemDC.h"

namespace WINUI
{

	CBasicWindowLessMemDC::CBasicWindowLessMemDC(void)
	{
		m_hMem = NULL;
		m_cx = 0;
		m_cy = 0;
		m_hBitmap = NULL;
		m_pBits = NULL;
	}

	CBasicWindowLessMemDC::~CBasicWindowLessMemDC(void)
	{
		if (m_hMem)
			::DeleteDC(m_hMem);
		if (m_hBitmap)
			::DeleteObject(m_hBitmap);
		m_hBitmap = NULL;
		m_hMem = NULL;
	}

	bool CBasicWindowLessMemDC::CreateDIB(HDC hdc,int cx,int cy)
	{
		if (m_hBitmap)
		{
			::DeleteObject(m_hBitmap);
			m_hBitmap = NULL;
		}

		m_bmpHeader.biSize = sizeof(m_bmpHeader);
		m_bmpHeader.biBitCount = 32;
		m_bmpHeader.biCompression = BI_RGB;
		m_bmpHeader.biWidth = cx;
		m_bmpHeader.biHeight = -cy;
		m_bmpHeader.biPlanes = 1;
		m_hBitmap = CreateDIBSection(hdc, (BITMAPINFO *)&m_bmpHeader, DIB_RGB_COLORS, (void **)&m_pBits, NULL, 0);
		if (m_hMem)
			::SelectObject(m_hMem,m_hBitmap);
		return m_hBitmap != NULL;
	}

	void CBasicWindowLessMemDC::SetMemSize(HDC hDC,int cx,int cy)
	{
		if (m_hMem == NULL)
		{
			m_cx = cx;
			m_cy = cy;

			m_hMem = ::CreateCompatibleDC(hDC);
			CreateDIB(hDC,cx,cy);
			ClearRect(0,0,cx,cy);
			return;
		}

		if (m_cx == cx && m_cy == cy)
			return;

		m_cx = cx;
		m_cy = cy;

		CreateDIB(hDC,cx,cy);
		ClearRect(0,0,cx,cy);
	}

	void CBasicWindowLessMemDC::ClearRect(int x,int y,int cx,int cy)
	{
		if (x <0)
			x = 0;
		if (y <0)
			y = 0;
		if (cx <0)
			cx = 0;
		if (cy <0)
			cy = 0;

		if (!m_pBits)
			return;

		for(int i=x;i<x+cx && i<m_bmpHeader.biWidth;i++)
		{
			for(int j=y;j<y+cy && j<-m_bmpHeader.biHeight;j++)
			{
				DWORD* pSrc = (DWORD*) m_pBits;
				pSrc += j*m_bmpHeader.biWidth+i;
				*pSrc = 0;
			}
		}
	}
}